package com.onstar.cn.framework.mvp.base.core;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;

import java.util.List;


public class NetworkUtil {
    public final static int NO_CONNECT = 0;
    public final static int WIFI = 1;
    public final static int MOBILE = 2;

    public static int checkNetworkInfo(Context context) {
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            State wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                    .getState();
            if (wifi == State.CONNECTED) {
                return WIFI;
            } else {
                NetworkInfo mobileNetworkInfo = connMgr
                        .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if (mobileNetworkInfo != null
                        && mobileNetworkInfo.getState() == State.CONNECTED) {
                    return MOBILE;
                }
            }
        }
        return NO_CONNECT;
    }

    public static boolean isConnect(Context context){
        return checkNetworkInfo(context) != NO_CONNECT;
    }

    /**
     *判断当前应用程序处于前台还是后台
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

}
